//
//  FirDetailController.m
//  ShopDemo
//
//  Created by 飞扬的青春 on 2018/7/15.
//  Copyright © 2018年 飞扬的青春. All rights reserved.
//

#import "FirDetailController.h"
#import "ShopDetailController.h"

@interface FirDetailController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *listCollectionview;
@property(nonatomic,assign)NSInteger pageindex;
@property(nonatomic,assign)NSInteger pagesize;
@property(nonatomic,strong)MineButton *pricebtn;
@property(nonatomic,strong)NSMutableArray *goodsArray;

@end

@implementation FirDetailController
-(NSMutableArray *)goodsArray{
    if (!_goodsArray) {
        _goodsArray = [NSMutableArray arrayWithCapacity:10];
    }
    return _goodsArray;
}
-(NSMutableArray *)imageArray{
    if (!_imageArray) {
        _imageArray = [NSMutableArray arrayWithCapacity:10];
    }
    return _imageArray;
}

-(void)priceButtonAction:(MineButton *)sender{
    if ([self.pricebtn.titleLabel.text isEqualToString:@"价格由低到高"]) {
        [self.pricebtn setTitle:@"价格由高到低" forState:UIControlStateNormal];
        NSArray *newarray = [self.imageArray sortedArrayUsingComparator:
                             ^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
                                 NSComparisonResult result = [@([obj2[@"GOODS_MINPRICE"] floatValue]) compare:@([obj1[@"GOODS_MINPRICE"]floatValue])];
                                 return result;
                             }];
        self.imageArray = [newarray mutableCopy];
    }else{
        NSArray *newarray = [self.imageArray sortedArrayUsingComparator:
                             ^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
                                 NSComparisonResult result = [@([obj1[@"GOODS_MINPRICE"] floatValue]) compare:@([obj2[@"GOODS_MINPRICE"]floatValue])];
                                 return result;
                             }];
        self.imageArray = [newarray mutableCopy];
        [self.pricebtn setTitle:@"价格由低到高" forState:UIControlStateNormal];
    }
    [self.listCollectionview reloadData];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.pricebtn = [MineButton buttonWithType:UIButtonTypeCustom];
    self.pricebtn.titleLabel.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
    [self.pricebtn setTitle:@"价格由低到高" forState:UIControlStateNormal];
    [self.pricebtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.pricebtn addTarget:self action:@selector(priceButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.pricebtn];
    self.pricebtn.sd_layout
    .topSpaceToView(self.view, 0)
    .centerXEqualToView(self.view)
    .heightIs(50*kJLXWidthScale)
    .widthIs(130*kJLXWidthScale);
    self.pageindex = 1;
    [self creatCollectionViewMethod];
    if (self.imageArray && self.imageArray.count > 0 && !self.urlStr) {
        
    }else{
        [self showDetailImageDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:self.urlStr]];
        self.listCollectionview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (self.pagesize == 10) {
                 self.pageindex ++;
                NSString *urlstr = [NSString stringWithFormat:@"/dashop/goods/app/list.do?GOODS_CATEGORY=%@&CurrentPage=%ld",self.dic[@"CATEGORY_ID"],self.pageindex];
                [self showDetailImageDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:urlstr]];
            }else{
                [self.listCollectionview.mj_footer endRefreshingWithNoMoreData];
//                [self.listCollectionview reloadData];
            }
        }];
    }
    
   
}


-(void)creatCollectionViewMethod{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.listCollectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 50*kJLXWidthScale, kScreenWidth, kScreenHeight - 120*kJLXWidthScale) collectionViewLayout:layout];
    self.listCollectionview.backgroundColor = [UIColor whiteColor];
    self.listCollectionview.dataSource = self;
    self.listCollectionview.delegate = self;
    [self.listCollectionview registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    [self.view addSubview:self.listCollectionview];
    
    
    
}


-(void)showDetailImageDataMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSArray *arr = response;
//        self.pagesize = arr.count;
        NSInteger numsize = 0;
        for (NSDictionary *dic in arr) {
            if (self.goodsArray.count == 0) {
                numsize ++;
                [self.imageArray addObject:dic];
                [self.goodsArray  addObject:dic[@"GOODS_ID"]];
            }else{
                if (![self.goodsArray containsObject:dic[@"GOODS_ID"]]) {
                    numsize ++;
                    [self.imageArray addObject:dic];
                    [self.goodsArray  addObject:dic[@"GOODS_ID"]];
                }
                
            }
        }
        self.pagesize = numsize;
        NSArray *newarray = [self.imageArray sortedArrayUsingComparator:
                             ^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
                                 NSComparisonResult result = [@([obj1[@"GOODS_MINPRICE"] floatValue]) compare:@([obj2[@"GOODS_MINPRICE"]floatValue])];
                                 return result;
                }];
        self.imageArray = [newarray mutableCopy];
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self.listCollectionview.mj_footer endRefreshing];
            [self.listCollectionview reloadData];
        }];
    } failBlock:^(NSError *error) {
        
    }];
    
}



#pragma mark -- collertionView.dataSource
//返回item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageArray.count;
    
    
}
//返回cell 对于每一item返回一个cell对象（重用机制）
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSDictionary *subdic = self.imageArray[indexPath.row];
    NSString *urlstr = subdic[@"GOODS_PIC"];
    UIImageView *imagevi = [UIImageView new];
    NSURL *uRL = [NSURL URLWithString:[MethodClass returnUrlSetStrWSDLURL:urlstr]];
    [imagevi sd_setImageWithURL:uRL];
    [cell.contentView addSubview:imagevi];
    imagevi.sd_layout
    .topSpaceToView(cell.contentView, 0)
    .centerXEqualToView(cell.contentView)
    .centerYEqualToView(cell.contentView)
    .widthIs(kScreenWidth/2 - 2 - 40*kJLXWidthScale)
    .heightIs(kScreenWidth/2 - 2 - 40*kJLXWidthScale);
    
    UILabel *titlab = [UILabel new];
    titlab.font = [UIFont systemFontOfSize:15*kJLXWidthScale];
    titlab.textAlignment = NSTextAlignmentCenter;
    titlab.textColor = [UIColor blackColor];
    titlab.numberOfLines = 0;
    titlab.text = [NSString stringWithFormat:@"%@",subdic[@"GOODS_NAME"]];
    [cell.contentView addSubview:titlab];
    titlab.sd_layout
    .topSpaceToView(imagevi, 0)
    .rightSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .leftSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .heightIs(20*kJLXWidthScale);
    
    UILabel *pricelab = [UILabel new];
    pricelab.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
    pricelab.textAlignment = NSTextAlignmentLeft;
    pricelab.textColor = [UIColor orangeColor];
    pricelab.text = [NSString stringWithFormat:@"￥%@",subdic[@"GOODS_MINPRICE"]];
    [cell.contentView addSubview:pricelab];
    pricelab.sd_layout
    .topSpaceToView(titlab, 0)
    .rightSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .leftSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .heightIs(20*kJLXWidthScale);
    return cell;
}
//返回分区数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

#pragma mark -- UICollectionViewDelegate
//点击item时
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ShopDetailController *shopVC = [[ShopDetailController alloc]init];
    NSDictionary *dic = self.imageArray[indexPath.row];
    shopVC.navigationItem.title = dic[@"GOODS_KEYWORDS"];
     NSString *urlstr = [NSString stringWithFormat:@"/dashop/goods/app/getGoods?GOODS_ID=%@&USER_ID=%@",dic[@"GOODS_ID"],[UserDefault objectForKey:LogUserID]];
    shopVC.urlStr = urlstr;
    shopVC.usdic = dic;
    [self.navigationController pushViewController:shopVC animated:YES];
}
//动态设置每个item的尺寸大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
        return CGSizeMake(kScreenWidth/2 - 2, kScreenWidth/2 - 2);
    
    
    
}
//最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
//最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}



////动态返回每个分区页脚的尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    return section == 0 ? CGSizeMake(100, 100) :CGSizeMake(200, 200);
//}
//动态设置item的缩进量
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
        return UIEdgeInsetsMake(10*kJLXWidthScale, 1, 10*kJLXWidthScale, 1);
   
}

//封装提示框方法
-(void)alerWithMessage:(NSString *)msg{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        //延迟1秒自动消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}

@end
